﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Caching;
using System.Web.Mvc;
using BilibiliIMGBLL;
using BiliBiliiMG.Model;
using Newtonsoft.Json;

namespace BiliBiliiMG
{
    public class IndexController : Controller
    {
        #region 页面
        /// <summary>
        /// 主页
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 留言
        /// </summary>
        /// <returns></returns>
        public ActionResult Opinion()
        {
            return View();
        }

        

        #endregion
        #region 方法
        /// <summary>
        /// 
        /// 写入留言
        /// </summary>
        /// <returns></returns>
        public bool LeaveComments(LeaveCommentsModel model)
        {
            LeaveCommentsBll bll = new LeaveCommentsBll();
            bll.Add(model);
            return true;
        }

        /// <summary>
        /// 找到IMG的URL
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public string GetInfo(string url)
        {
            long n = 0;
            long avhm = 0;
            var imgUrl = "";
            var title = "";
            var tishi = "";
            try
            {
                if (long.TryParse(url, out n))
                {
                    //为数字 
                    avhm = long.Parse(url);
                    url = "av" + url;
                }
                else
                {
                    avhm = long.Parse(url.Substring(2));
                }
                if (HttpContext.Cache[url] == null||string.IsNullOrEmpty(HttpContext.Cache[url].ToString()))
                {
                    var html = WebParities("https://www.bilibili.com/video/" + url + "/");
                    imgUrl = GetString(html, "<img src=\"", "\" ", false);
                    title = GetString(html, "<h1 title=\"", "\">", false);
                    tishi = GetString(html, "document.write(\"", "\"", false);
                    if (imgUrl == "//static.hdslb.com/images/12377.png" || tishi == "对不起，你输入的参数有误！")
                    {
                        //从接口拿到数据
                        var info = WebParities("http://www.jijidown.com/API/AvToCid/" + avhm);
                        ApiInfo model = JsonConvert.DeserializeObject<ApiInfo>(info);
                        if (model.list.Count == 0 && string.IsNullOrEmpty(model.img))
                        {
                            return "{ \"error\":\"true\"}";
                        }
                        else
                        {
                            imgUrl = model.img;
                            title = model.title;
                        }
                    }
                    IoCache(imgUrl, title, url, avhm);
                    return "{\"imgUrl\":\"" + imgUrl + "\", \"title\":\"" + title + "\", \"av\":\"" + url + "\", \"error\":\"false\", \"avhm\":\"" + avhm + "\"}";
                }
                else
                {
                    return HttpContext.Cache[url].ToString();
                }

            }
            catch (Exception ex)
            {
                return "{ \"error\":\"true\",\"errorinfo\":" + ex + " }";
            }
        }

        /// <summary>
        /// 给图片写缓存
        /// </summary>
        /// <param name="imgUrl">图片URL</param>
        /// <param name="title">视频标题</param>
        /// <param name="url">视频地址</param>
        /// <param name="avhm">av号码</param>
        /// <returns></returns>
        public bool IoCache(string imgUrl = "$$", string title = "$$", string url = "$$", long avhm = -1)
        {
            string text = "{\"imgUrl\":\"" + imgUrl + "\", \"title\":\"" + title + "\", \"av\":\"" + url +
                          "\", \"error\":\"false\", \"avhm\":\"" + avhm + "\"}";
            HttpContext.Cache.Insert(url, text, null, DateTime.Now.AddDays(1), Cache.NoSlidingExpiration);
            if (HttpContext.Cache[url].ToString() == text)
            {
                return true;
            }
            else
            {
                HttpContext.Cache[url] = text;
                return false;
            }

        }

        /// <summary>
        /// 获取字符串中的指定内容
        /// </summary>
        /// <param name="Data">需要分析的字符串</param>
        /// <param name="Start">从该字符串开始截取,留空表示从开头截取</param>
        /// <param name="End">截取到该字符串结束,留空表示直接截取到末尾</param>
        /// <param name="Stay">是否保留截取字符串的头尾</param>
        /// <returns></returns>
        public static string GetString(string Data, string Start, string End, bool Stay)
        {
            //此方法是针对之前的GetString进行的改进，修复了之前方法的一个BUG：End字符串被包含在Start字符串中的时候返回结果为空的问题
            try
            {
                int StartIndex;//起始索引
                int StartLenth;//起始字符串长度
                int EndIndex;//结束索引
                int EndLenth;//结束字符串长度
                StartLenth = Start.Length;
                EndLenth = End.Length;
                if (!Stay)
                {
                    //不保留头尾字段
                    StartIndex = (Start == string.Empty) ? 0 : Data.IndexOf(Start) + StartLenth;
                    string strt = Data.Substring(StartIndex, Data.Length - (StartIndex));
                    EndIndex = (End == string.Empty) ? Data.Length - StartIndex : Data.Substring(StartIndex, Data.Length - (StartIndex)).IndexOf(End);
                }
                else
                {
                    //保留头尾字段
                    StartIndex = (Start == string.Empty) ? 0 : Data.IndexOf(Start) + StartLenth;
                    string strt = Data.Substring(StartIndex, Data.Length - (StartIndex));
                    EndIndex = (End == string.Empty) ? Data.Length - StartIndex : Data.Substring(StartIndex, Data.Length - (StartIndex)).IndexOf(End);
                    StartIndex = StartIndex - StartLenth;
                    EndIndex = EndIndex + EndLenth + StartLenth;
                }
                return Data.Substring(StartIndex, EndIndex);
            }
            catch { return ""; }
        }

        /// <summary>
        ///模拟浏览器请求
        /// </summary>
        public string WebParities(string url, string cookies = "")
        {

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Timeout = 30000;
            HttpWebResponse myWebResponse = webRequest.GetResponse() as HttpWebResponse;
            Stream st = myWebResponse.GetResponseStream();
            if (myWebResponse.ContentEncoding.ToLower().Contains("gzip"))
            {
                st = new GZipStream(st, CompressionMode.Decompress);
            }
            using (StreamReader sr = new StreamReader(st, Encoding.UTF8))
            {
                string Temp = sr.ReadToEnd();
                st.Close();//关闭资源
                myWebResponse.Close();
                webRequest.Abort();//释放
                return Temp;
            }
        }
        #endregion
    }
}